﻿Imports System.Net.Sockets

Public Class cls_socket
    ' init socket
    Private clientSocket As System.Net.Sockets.TcpClient
    Private serverStream As NetworkStream

    Dim Server As String
    Dim Port As String

    Public Sub New(ByVal Server As String, ByVal Port As String)
        Me.Server = Server
        Me.Port = Port
    End Sub

    Public Function Connect() As Boolean
        Try
            clientSocket = New System.Net.Sockets.TcpClient(Me.Server, Me.Port)
            'clientSocket.Connect(Me.Server, Me.Port)
            serverStream = clientSocket.GetStream()
            Return True
        Catch ex As Exception
            'MsgBox("Function Connect in Class : cls_socket : " & ex.Message)
            Return False
        End Try
    End Function

    Public Sub Disconnect()
        Try
            clientSocket.Close()
        Catch ex As Exception
            'MsgBox(ex.Message)
        End Try
    End Sub

    Public Function IsConnected() As Boolean
        Try
            If clientSocket.Connected Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Return False
        End Try
    End Function

    Public Function SendMessage(ByVal strData As String) As String

        Try
            ' Send Message
            Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes(strData)
            serverStream.Write(outStream, 0, outStream.Length)
            serverStream.Flush()

            ' Get Message
            serverStream = clientSocket.GetStream()
            Dim buffSize As Integer
            Dim inStream(10024) As Byte

            buffSize = clientSocket.ReceiveBufferSize
            serverStream.Read(inStream, 0, buffSize)

            Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream)

            Return returndata

        Catch ex As Exception
            Return "Error"
        End Try

    End Function

End Class
